from django.db.models import Count
from django.http import JsonResponse
from django.shortcuts import render

from web import models


def statistics(request, project_id):
    return render(request, 'statistics.html')


def pie_info(request, project_id):
    """希望得到这个最终列表
        [
            {"name":"高","y":2},
            {"name":"中","y":1},
        ]
        先构造一个字典1：
        {
            “danger”：{name:"高"，"y":0}
            "warning":{name:"中"，"y":0}
            "success":{name:"低"，"y":0}
        }
        再从数据库得到列表1：
     [
        {"priority':danger',"ct":1},
        {"priority':success',"ct":2},
     ]
    """
    start = request.GET.get("start")
    end = request.GET.get("end")
    # 生成字典1
    data_dict = {}
    choices = models.Issues.priority_choices
    for key, text in choices:
        data_dict[key] = {"name": text, "y": 0}
    # 从数据库得到列表1
    list1 = models.Issues.objects.filter(project_id=project_id,create_datetime__gt=start,create_datetime__lt=end).values("priority").annotate(ct=Count("id"))
    for item in  list1:
        data_dict[item["priority"]]["y"] = item["ct"]
    return JsonResponse({"status": True, "data":list(data_dict.values())})


def line_info(request, project_id):
    """
      {
        categories:['苹果', '橘子', '梨'],
        series:[{
            name: '新建',
            data: [5, 3, 4]
        }, {
            name: '处理中',
            data: [2, 2, 3]
        }, {
            name: '已完成',
            data: [3, 4, 4]
        }]
    }
    先构造dict1={
（是userid） 1:{
            name:ayerjo，
            data:{
               1:0,
               2:0,
               3:0,
               4:0,
               5:0,
               6:0,
               7:0,
               }
           }
        2:{
            name:wangmeng，
            data:{
               1:0,
               2:0,
               3:0,
               4:0,
               5:0,
               6:0,
               7:0,
                 }
           }
    }
    从数据库循环issues列表：
    for item in (issuees_obj1,issuees_obj2):
         if item.assign:
            dict[item.assign_id][data][item.status] +=1
        else:
            dict[None][data][item.status] +=1

    再构造dict2=
        {1(是status):{
            name: '新建',
            data: []
        },
        2：{
            name: '处理中',
            data: []
        }
        }

    再通过循环choices(
        (1, '新建'),
        (2, '处理中'),
    )
    将for key,text in choices:
        for item in dict1.values():
            count =  item["data"][key]
            dict2[key]["data“].append(count)
        最后得到的dict2.values()就为前端所需的series
    """
    start = request.GET.get("start")
    end = request.GET.get("end")
    data_dict = {}
    # 1.项目成员
    data_dict[request.manage.creator_id] = {"name":request.manage.creator.username,# 创建者
                                              "data":{item[0]:0 for item in models.Issues.status_choices}}
    data_dict["No"]={"name":"未指派",
                     "data": {item[0]: 0 for item in models.Issues.status_choices}}
    for item in models.ProjectUser.objects.filter(project_id=project_id): #参与者
        data_dict[item.user_id]={
            "name":item.user.username,
            "data":{item[0]:0 for item in models.Issues.status_choices}
        }
    # 2.从数据库循环往字典加数据
    for item in models.Issues.objects.filter(project_id=project_id,create_datetime__gt=start,create_datetime__lt=end):
        if item.assign:
            data_dict[item.assign_id]["data"][item.status] +=1
        else:
            data_dict["No"]["data"][item.status] +=1
    # 3.构造字典2
    dict2 ={}
    for key,text in models.Issues.status_choices:
        dict2[key] = {"name":text,"data":[]}
    # 用两个字典循环往里添加值
    for key,text in models.Issues.status_choices:
        for item in data_dict.values():
            count = item["data"][key]
            dict2[key]["data"].append(count)

    context = {
        "status":True,
        "categories":[item["name"] for item in data_dict.values()],
        "series":list(dict2.values())
    }
    return JsonResponse(context)